<template>
    <el-dialog :title="dialogTitle" :visible.sync="visible" width="960px" :close-on-click-modal="false" append-to-body>
        <div class="form-box">
            <!-- 信息总览（订单/包赔/售后） -->
            <el-descriptions :column="3" border :labelStyle="{ minWidth: '80px', width: '80px', textAlign: 'right' }"
                :contentStyle="{ minWidth: '100px', textAlign: 'left' }">
                <template slot="title">
                    <div @click="toggleOrderInfo" style="cursor: pointer;">
                        订单信息 <i :class="orderInfoExpanded ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"></i>
                    </div>
                </template>

                <template v-if="orderInfoExpanded">
                    <el-descriptions-item label="中介单号">{{ detail.orderNo }}</el-descriptions-item>
                    <el-descriptions-item label="售后单号">{{ detail.afterNo }}</el-descriptions-item>
                    <el-descriptions-item label="售后状态">
                        <el-tag :type="afterStatusType(detail.afterStatus)">{{ afterStatusText(detail.afterStatus)
                            }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="游戏账号">{{ detail.account }}</el-descriptions-item>
                    <el-descriptions-item label="卖家昵称">{{ detail.sellerNickname }}</el-descriptions-item>
                    <el-descriptions-item label="创建时间">{{ detail.createTime }}</el-descriptions-item>


                    <el-descriptions-item label="换绑截图">
                        <img-box :height="40" :img="orderInfos.bindingScreenshot"></img-box>
                    </el-descriptions-item>
                    <el-descriptions-item label="支付截图">
                        <img-box :height="40" :img="orderInfos.paymentScreenshot"></img-box>
                    </el-descriptions-item>
                    <el-descriptions-item label="放款截图">
                        <img-box :height="40" :img="orderInfos.loanScreenshot"></img-box>
                    </el-descriptions-item>
                    <el-descriptions-item label="商品金额">
                        <span style="color:red">¥{{ formatMoney(orderInfos.productAmount) }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="包赔费">
                        <span style="color:red">¥{{ formatMoney(orderInfos.compensationFee) }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="手续费">
                        <span style="color:red">¥{{ formatMoney(orderInfos.serviceFee) }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="总金额">
                        <span style="color:red">¥{{ formatMoney(orderInfos.totalAmount) }}</span>
                    </el-descriptions-item>
                </template>
            </el-descriptions>

            <div style="height:20px"></div>
            <el-descriptions  :column="3" border
                :labelStyle="{ minWidth: '80px', width: '80px', textAlign: 'right' }"
                :contentStyle="{ minWidth: '100px', textAlign: 'left' }" @title-click="toggleAfterSale">
                 <template slot="title">
                    <div @click="toggleAfterSale" style="cursor: pointer;">
                        售后申请信息 <i :class="afterSaleExpanded ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"></i>
                    </div>
                </template>
                <template v-if="afterSaleExpanded">
                    <el-descriptions-item label="售后编号">{{ detail.afterNo }}</el-descriptions-item>
                    <el-descriptions-item label="申请人">{{ detail.applicantName }}</el-descriptions-item>
                    <el-descriptions-item label="申请时间">{{ detail.createTime }}</el-descriptions-item>
                    <el-descriptions-item label="买家">{{ detail.buyerNickname }}</el-descriptions-item>
                    <el-descriptions-item label="卖家">{{ detail.sellerNickname }}</el-descriptions-item>

                    <el-descriptions-item label="问题描述">
                        <span style="white-space: pre;">{{ detail.afterReason }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="图片附件">
                        <div class="img-box flex">
                            <div style="display:flex; gap:8px; flex-wrap: wrap;">
                                <el-image v-for="(img, idx) in applicantImgArr" :key="idx" :src="img"
                                    style="width: 100px; " fit="contain" :preview-src-list="applicantImgArr" />
                            </div>
                        </div>
                    </el-descriptions-item>
                </template>
            </el-descriptions>
            <div style="height:20px"></div>
            <el-descriptions v-if="guaranteeInfo && guaranteeInfo.name"
              :column="3" border
                :labelStyle="{ minWidth: '80px', width: '80px', textAlign: 'right' }"
                :contentStyle="{ minWidth: '100px', textAlign: 'left' }" >
                 <template slot="title">
                    <div @click="toggleCompensation" style="cursor: pointer;">
                        包赔资料 <i :class="compensationExpanded ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"></i>
                    </div>
                </template>
                <template v-if="compensationExpanded">
                    <el-descriptions-item label="卖家姓名">{{ guaranteeInfo.name }}</el-descriptions-item>
                    <el-descriptions-item label="身份证号">{{ guaranteeInfo.idCard }}</el-descriptions-item>
                    <el-descriptions-item label="手机号">{{ guaranteeInfo.phoneNumber }}</el-descriptions-item>
                    <el-descriptions-item label="地址" :span="3">{{ guaranteeInfo.adress }}</el-descriptions-item>
                    <!-- <el-descriptions-item label="卖家" v-if="orderInfo.backClueOrder">{{orderInfo.backClueOrder.sellerName}}</el-descriptions-item> -->
                    <el-descriptions-item label="家庭人员" :span="3">
                        <span style="white-space: pre;">{{ guaranteeInfo.familyRemark }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="其他信息" :span="3">
                        <span style="white-space: pre;">{{ guaranteeInfo.otherRemark }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="图片" :span="3">
                        <div class="img-box flex">
                            <div style="display:flex; gap:8px; flex-wrap: wrap;">
                                <el-image v-for="(img, idx) in baopeiImgs" :key="idx" :src="getImgUrl(img)"
                                    style="width: 80px; height: 80px;" fit="cover"
                                    :preview-src-list="baopeiImgs.map(getImgUrl)" />
                            </div>
                        </div>
                    </el-descriptions-item>
                </template>
            </el-descriptions>
            <div style="height:20px"></div>

            <!-- 处理表单（同意/拒绝） -->
            <el-form ref="processFormRef" :model="processForm" :rules="formRules" label-width="100px">
                <el-form-item :label="isAgree ? '同意原因' : '拒绝原因'" prop="processingResult">
                    <el-input type="textarea" :rows="3" v-model="processForm.processingResult" placeholder="请输入处理结果" />
                </el-form-item>
                <el-form-item label="赔付金额" prop="compensationAmount" v-if="isAgree">
                    <el-input v-model="processForm.compensationAmount" placeholder="请输入赔付金额" />
                </el-form-item>
                <el-form-item label="处理截图">
                    <el-upload :action="uploadImgUrl" :file-list="imgShowList" list-type="picture-card"
                        :on-preview="handlePictureCardPreview" :on-exceed="uploadNumber" :multiple="true" :drag="true"
                        :on-success="handleUploadSuccess" :limit="10" :on-remove="handleRemove" :headers="headers">
                        <div class="uploadbg">
                            <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/uploadbg.png" alt="">
                            <br />
                            <span>上传图片</span>
                        </div>
                    </el-upload>


                    <!-- <uploadImageOne v-model="processForm.processingScreenshot" /> -->
                </el-form-item>
            </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取 消</el-button>
            <el-button type="primary" :loading="submitting" @click="onSubmit">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import uploadImageOne from "@/components/upload/uploadImageOne.vue";
import { agree, refusee, orderInfo } from "@/api/interOrder/index";

export default {
    name: 'InterSalesProcessDialog',
    components: { uploadImageOne },
    data() {
        return {
            visible: false,
            dialogTitle: '',
            isAgree: true,
            submitting: false,
            // 详情展示数据
            detail: {},
            applicantImgArr: [],
            baopeiImgs: [],
            guaranteeInfo: {},
            orderInfos: {},
            // 表单
            processForm: {
                id: undefined,
                processingResult: '',
                processingScreenshot: '',
                compensationAmount: null,
            },
            uploadImgUrl: "",
            headers: {},
            imgShowList: [],
            newImages: [],
            imgFileList: [],
            // 展开收起状态
            orderInfoExpanded: true,
            afterSaleExpanded: true,
            compensationExpanded: true,
        }
    },
    computed: {
        formRules() {
            return {
                processingResult: [{ required: true, message: this.isAgree ? '请输入同意原因' : '请输入拒绝原因', trigger: 'blur' }],
                compensationAmount: this.isAgree ? [{ required: true, message: '请输入赔付金额', trigger: 'blur' }] : [],
            }
        }
    },
    created() {
        this.headers = {
            Authorization: "Bearer " + getToken(),
        };
        this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
    },
    methods: {
        async open(row, type) {
             this.orderInfoExpanded =  true,
            this.afterSaleExpanded =  true,
            this.compensationExpanded = true,
            this.visible = true;
            this.newImages = [];
            this.imgShowList = [];
            this.imgFileList = [];
            this.isAgree = type === 'agree';
            this.dialogTitle = this.isAgree ? '同意售后' : '拒绝售后';
            const res = await orderInfo(row.orderId)
            this.orderInfos = res.data
            // 明细
            this.detail = row || {};
            if (row && row.afterScreenshot) {
                this.applicantImgArr = row.afterScreenshot.split(',');
            } else {
                this.applicantImgArr = [];
            }
            // 解析包赔资料
            this.baopeiImgs = [];
            if (row && row.compensationMaterials) {
                try {
                    const info = JSON.parse(row.compensationMaterials);
                    this.guaranteeInfo = JSON.parse(row.compensationMaterials)

                    let imgs = [];
                    if (info.emblemIdcardImg) imgs.push(info.emblemIdcardImg);
                    if (info.faceIdcardImg) imgs.push(info.faceIdcardImg);
                    if (info.img) {
                        const arr2 = JSON.parse(info.img);
                        if (arr2 && arr2.length) {
                            arr2.forEach(r => { if (r.url) imgs.push(r.url); });
                        }
                    }
                    this.baopeiImgs = imgs;
                } catch (e) {
                    this.baopeiImgs = [];
                }
            }
            // 表单
            this.processForm = {
                id: row && row.id,
                processingResult: '',
                processingScreenshot: '',
                compensationAmount: null,
            };
            this.$nextTick(() => {
                if (this.$refs.processFormRef) this.$refs.processFormRef.clearValidate();
            });
        },
        onSubmit() {
            this.$refs.processFormRef.validate(valid => {
                if (!valid) return;
                console.log(this.newImages, this.imgFileList)
                if (this.newImages && this.newImages.length) {
                    let newArr = [];
                    this.newImages.forEach((img) => {
                        newArr.push({
                            name: img.name,
                            url: img.response.data.filePath,
                        });
                    });
                    this.processForm.processingScreenshot = JSON.stringify(
                        this.imgFileList.concat(newArr)
                    );
                } else {
                    this.processForm.processingScreenshot = JSON.stringify(this.imgFileList);
                }

                this.submitting = true;
                const payload = { ...this.processForm };
                const req = this.isAgree ? agree(payload) : refusee(payload);

                req.then(() => {
                    this.$message.success(this.isAgree ? '已同意售后' : '已拒绝售后');
                    this.visible = false;
                    this.$emit('success');
                }).finally(() => {
                    this.submitting = false;
                });
            });
        },
        afterStatusText(val) { const map = { 1: '待处理', 2: '已同意', 3: '已拒绝' }; return map[val] || '-'; },
        afterStatusType(val) { switch (val) { case 1: return 'warning'; case 2: return 'success'; case 3: return 'danger'; default: return 'info'; } },
        formatMoney(n) { if (n === 0) return '0.00'; if (!n) return '---'; return Number(n).toFixed(2); },
        getImgUrl(item) { return typeof item === 'string' ? item : (item && item.url) || ''; },
        // 详情图片上传成功
        handleUploadSuccess(res, file, fileList) {
            if (res.code == 200) {
                // 取得新上传的文件
                this.newImages = fileList.filter((t) => {
                    return t.url.indexOf("blob:") > -1;
                });
            }
        },
        // 详情图片删除
        handleRemove(response, fileList, file) {
            const that = this;
            // 1.获取将要删除图片的临时路径
            const filePath = response.url;
            // 2.找到图片对应的索引值
            this.imgFileList.forEach(function (element, key) {
                if (element.url === filePath) {
                    that.imgFileList.splice(key, 1); //回显的图片
                }
            });
            this.newImages.forEach(function (element, key) {
                if (element.url === filePath) {
                    that.newImages.splice(key, 1); //新上传的图片
                }
            });
        },
        // 图片预览
        handlePictureCardPreview(file) {
            this.$viewerApi({
                images: [file.url],
            });
        }, uploadNumber(file, fileList) {
            //限制图片数量
            this.$modal.msgError("最多只能上传10张图片");
        },

        // 展开收起方法
        toggleOrderInfo() {
            console.log('toggleOrderInfo')
            this.orderInfoExpanded = !this.orderInfoExpanded;
        },
        toggleAfterSale() {
            this.afterSaleExpanded = !this.afterSaleExpanded;
        },
        toggleCompensation() {
            this.compensationExpanded = !this.compensationExpanded;
        },

    }
}
</script>

<style scoped lang="scss">
::v-deep .el-upload-dragger {
    width: 100px;
    border: none;
    height: auto;
    margin: 10px auto 0;
    line-height: 30px;
}

::v-deep .uploadbg {
    margin-top: 5px;
}

// 展开收起样式
::v-deep .el-descriptions__title {
    cursor: pointer;
    user-select: none;

    &:hover {
        color: #409EFF;
    }
}
</style>
